/**
 * weapp-js
 * https://code.aliyun.com/jionglee/weapp_base.git
 * Copyright@ 2020 Motigo, Inc.
 * 
 */
import ConsoleLog from "./log.js";
import request_cache from './request_cache.js';

let isLoading = false;

export default {
    HOST: '',
    appid: '',
    user_openid: '',
    user_unionid: '',
    session_id: '',
    init(session_id, appid, unionid, openid) { // init接口留着是兼容：之前的设计
        this._update_session(session_id, appid, openid, unionid);
    },
    set_host(host) {
        this.HOST = host;
    },
    // 禁用缓存：主要用于dev模式，外部统一禁用
    disable_cache() {
        request_cache.disable();
    },
    get(path, params, fromPath, enable_cache, expire_in) {
        return new Promise((resolve, reject) => {
            request_cache.get(path, params, enable_cache).then(data => {
                resolve(data);
            }, () => {
                this._request('GET', path, params, fromPath).then(data => {
                    resolve(data);
                    if (enable_cache === true || expire_in) {
                        request_cache.set(path, params, expire_in, data);
                    }
                }, err => {
                    reject(err);
                });
            });
        })
    },
    post(path, params, fromPath) {
        return this._request('POST', path, params, fromPath);
    },
    put(path, params) {
        return this._request('PUT', path, params);
    },
    delete(path, params) {
        return this._request('DELETE', path, params);
    },
    ensure() {
        return new Promise(resolve => {
            if (this.HOST) {
                resolve()
            } else {
                let timer = setInterval(() => {
                    if (this.HOST) {
                        clearInterval(timer);
                        resolve();
                    }
                }, 10)
            }
        });
    },
    _update_session(session_id, appid, openid, unionid) {
        this.session_id = session_id;
        this.appid = appid;
        this.user_unionid = unionid;
        this.user_openid = openid;
    },
    _request(method, path, params, fromPath) {
        let self = this;
        if (!self.appid) {
            const accountInfo = wx.getAccountInfoSync();
            self.appid = accountInfo.miniProgram.appId;
        }

        return new Promise((resolve, reject) => {
            wx.getNetworkType({
                success: (res) => {
                    const networkType = res.networkType;

                    if (networkType === "none") {
                        //   无网络
                        isLoading && wx.hideLoading();
                        isLoading = false;
                        if (fromPath) {
                            wx.redirectTo({
                                url: `/pages/error_page/index?fromPath=${fromPath}`,
                            });
                        }
                        reject("您的网络不好，请检查网络后重试");
                    } else {
                        self.ensure().then(() => {
                            isLoading = true;
                            wx.showLoading({
                                title: '加载中',
                                mask: true,
                            });
                            wx.request({
                                method: method,
                                timeout: 10000,
                                header: {
                                    'content-type': 'application/json',
                                    'appid': self.appid,
                                    'openid': self.user_openid,
                                    'unionid': self.user_unionid,
                                    'session': self.session_id
                                },
                                url: self.HOST + path,
                                data: params,
                                success(res) {
                                    isLoading && wx.hideLoading();
                                    isLoading = false;
                                    if (res.data.ret == 0) {
                                        resolve(res.data.data);
                                    } else {
                                        if (res.data.ret === -109) {
                                            if (fromPath) {
                                                wx.redirectTo({
                                                    url: `/pages/error_page/index?fromPath=${fromPath}`,
                                                });
                                            }
                                            reject("您的网络不好，请检查网络后重试");
                                            return
                                        }
                                        reject(res.data);

                                    }
                                },
                                fail(err) {
                                    isLoading && wx.hideLoading();
                                    isLoading = false;
                                    ConsoleLog.error(err)
                                    if (err.errMsg.includes('-109') || err.errMsg.includes('request:fail')) {
                                        if (fromPath) {
                                            wx.redirectTo({
                                                url: `/pages/error_page/index?fromPath=${fromPath}`,
                                            });
                                        }
                                        reject("您的网络不好，请检查网络后重试");
                                        return
                                    }
                                    reject(err)

                                }
                            })
                        });
                    }
                }
            });

        });
    }
}